package com.atguigu.gmall.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.product.client.ProductFeignClient;
import jdk.nashorn.internal.runtime.options.Options;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * ClassName: IndexController
 * Package: com.atguigu.gmall.controller
 * Description:
 *
 * @Author 刘轩
 * @Create 2023-08-26 8:47
 * @Version 1.0
 */

@Controller
public class IndexController {

 @Autowired
 private ProductFeignClient productFeignClient;

 @Autowired
 private TemplateEngine templateEngine;

 /**
  * 渲染首页
  * 首页分页数据展示
  * @param model
  * @return
  */
 @GetMapping({"/", "/index.html"})
 public String index(Model model) {
  //1.远程获取分类数据
  Result result = productFeignClient.getBaseCategoryList();

  //2.添加数据到模型对象Model
//model.addAllAttributes(result.getData());
  model.addAttribute("list",result.getData());

  //3.返回模板页面
  return "index/index.html";
 }

 /**
  * 创建模版
  * @return
  */

 @GetMapping("createIndex")
 @ResponseBody
 public Result createIndex(){
  //  获取分类数据
  Result result = productFeignClient.getBaseCategoryList();
  //  第一个模版名，第二个模版的内容，第三个数据流
  Context context = new Context();
  context.setVariable("list",result.getData());
  FileWriter fileWriter = null;
  try {
   fileWriter = new FileWriter("D:\\index.html");
  } catch (IOException e) {
   throw new RuntimeException(e);
  }
  templateEngine.process("index/index.html",context,fileWriter);
  return Result.ok();
 }
}
